package com.example.bbs.util;


import com.example.bbs.domain.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtil {


    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private int expiration;

    public String generateToken(String userId) {
        Map<String, Object> claim = new HashMap<>();
        claim.put("sub", userId);
        claim.put("created", new Date());
        String jwtToken = Jwts.builder().setClaims(claim)
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
        return jwtToken;
    }

    public boolean isValid(String jwtToken, User user) {
        if (StringUtils.isBlank(jwtToken) || user == null) return false;

        Claims body = Jwts.parser().setSigningKey(secret).parseClaimsJws(jwtToken).getBody();
        //判断是否过期
        Date expiration = body.getExpiration();
        if (expiration.before(new Date())) return false;
        //判断用户信息是否一致
        String userId = body.getSubject();
        if (!user.getUserId().equals(userId)) {
            return false;
        }
        return true;
    }

    public String refreshToken(String jwtToken) {
        Claims body = Jwts.parser().setSigningKey(secret).parseClaimsJws(jwtToken).getBody();
        Date date = body.getExpiration();

        if (date.getTime() - System.currentTimeMillis() <= 24 * 60 * 60 * 3) {
            body.put("created", new Date());
            jwtToken = Jwts.builder().signWith(SignatureAlgorithm.HS256, secret)
                    .setClaims(body).setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                    .compact();
            return jwtToken;
        }
        return null;
    }


    public String getUserId(String jwt) {
        Claims body = Jwts.parser().setSigningKey(secret).parseClaimsJws(jwt).getBody();
        return body.getSubject();
    }



}
